<?php

namespace app\web\controller;

use think\Db;
use \app\model\Withdrawal;
use \app\model\Channel;
use \app\model\Mch;
class User extends Base
{
    /**
     * Undocumented 下级商户
     *
     * @return void
     */
    public function index(){
        $list = Mch::where("agent_id",$this->request->auth_mch['mch_id'])->where(function($query){

        })->paginate(10,false,['query' =>$this->request->param()]);
        $page = $list->render();
        $this->assign("list",$list);
        $this->assign("page",$page);
        return view("index");
    }
    /**
     * Undocumented 更新商户状态、入金、出款
     *
     * @return boolean
     */
    public function is_mch(){
        $id = $this->request->param('mid');
        $type = $this->request->param('type',1);
        $info = Mch::where("id",$id)->find();
        if(!$info) return $this->error("数据不存在");
        $result = Mch::save_mch($type,$info);
        if($result === true){
            switch($type){
                case 'rj'://入金
                    $action = $info->rukuan == 1 ? '修改商户号['.$info->mch.']商户入金状态为:禁用' : '修改商户号['.$info->mch.']商户入金状态为:开启';
                break;
                case 'ck'://出款
                    $action = $info->chukuan == 1 ? '修改商户号['.$info->mch.']商户出款状态为:禁用' : '修改商户号['.$info->mch.']商户出款状态为:开启';
                break;
                default:  //商户状态
                $action = $info->status == 1 ? '修改商户号['.$info->mch.']商户状态为:禁用' : '修改商户号['.$info->mch.']商户状态为:开启';
            }
            getMchLog($this->request->auth_mch['mch'],$action,$this->request->auth_mch['is_agent']);
            return $this->success('操作成功');
        }
        return $this->error('操作失败');
    }
    /**
     * Undocumented 配置渠道
     *
     * @return void
     */
    public function configChannel(){
        if($this->request->isAjax()){
            $result = Mch::mch_config($this->request->param());
            if($result === true){
                getMchLog($this->request->auth_mch['mch'],'给商户'.$this->request->param('mch').'配置渠道',$this->request->auth_mch['is_agent']);
                return $this->success('操作成功');
            }else{
                return $this->error($result);
            }
        }else{
            $info = Mch::where("id",$this->request->param('pid'))->find();
            if(!$info){
                return $this->error("数据不存在",'/web/user');
            }
            //获取代理商配置渠道
            $channel_id = Db::name("agent_channel")->where("agent_id",$this->request->auth_mch['mch'])->column("channel_id");
            $payment_id = Db::name("agent_channel")->where("agent_id",$this->request->auth_mch['mch'])->column("payment_id");
            if(empty($channel_id)){
                $list = array();
            }else{
                $list = Channel::where('id','in',$channel_id)->field("id,title")->select()->toArray();
                foreach ($list as $key => $value) {
                    $payment = Db::name("payment")->where("channel_id",$value['id'])->where("id",'in',$payment_id)->select();
                    $list[$key]['list'] = $payment;
                    $list[$key]['count'] = count($payment);
                }
            }
            $arr = array();
            $at = get_list('mch_channel',$info->mch);
            if($at){
                foreach ($at as  $value) {
                    $arr[] = $value['payment'];
                }
            }
            $type = array();
            foreach ($arr as  $value) {
                $t = explode("|",$value);
                foreach ($t as  $v) {
                    $s = explode(":",$v);
                    $type[$v[0]]['pid'] = $s[0];
                
                    $type[$v[0]]['qaun'] = $s[2];
                    $type[$v[0]]['concurrent'] = $s[3];
                    $type[$v[0]]['run_rate'] = $s[1];
                } 
            }
        
            $info->type = $type;
            $this->assign("info",$info);
            $this->assign("list",$list);
            return view("config_channel");
        } 
    }
    /**
     * Undocumented 提现记录
     *
     * @return void
     */
    public function withdrawal(){
        $list = Withdrawal::alias('a')->order('a.id','desc')
        ->where("a.mch_id",$this->request->auth_mch['mch'])
        ->where(function($query){
            $status = input('status');
            if($status){
                $query->where("a.status",$status);
            }
            $keyword = input('keyword');
            if($keyword){
                $query->where("a.with_out_no",'like','%'.$keyword.'%');
            }
            $start = input("start",date('Y-m-d 00:00:00',time()));
            $end = input("end",date('Y-m-d 23:59:59',time()));
            if(!empty($start) && !empty($end)){
                $query->where("a.create_time",'between',[$start,$end]);
            }
        })->join('mm_bank_card b','a.bank_id = b.id')
        ->field('a.*,b.card_number,b.account_name,b.bank_name,b.branch,b.location')
        ->paginate(10,false,['query' =>$this->request->param()]);
        //银行卡
        $bank = Db::name("bank_card")->where("mch_id",$this->request->auth_mch['mch'])->field("id,card_number,bank_name")->select();
        $page = $list->render();
        
        $this->assign("bank",$bank);
        $this->assign("list",$list);
        $this->assign("page",$page);
        $info = Mch::where('mch',$this->request->auth_mch['mch'])->field('balance,freeze')->find();
        $this->assign("data",$this->request->param());
        $this->assign("info",$info);
        return view("withdrawal");
    }
    /**
     * Undocumented 添加/编辑银行卡
     *
     * @return void
     */
    public function saveBank(){
        $data = $this->request->param();
        //获取数据
        if(isset($data['type']) && $data['type'] == 1){
            $info = Db::name("bank_card")->where("id",$data['id'])->field("id,card_number,account_name,bank_name,branch,location")->find();
            if(empty($info)){
                return $this->error("暂无数据");
            }
            $location = explode(" - ",$info['location']);
            $info['province'] = $location[0];
            $info['city'] = $location[1];
            $info['district'] = $location[2];
            unset($info['location']);
            return $this->success("获取数据成功",'',$info);
        }
        //添加/修改
        $result = Withdrawal::backUpdate($data,$this->request->auth_mch['mch']);

        if($result === true){
            return $this->success("操作成功");
        }else{
            return $this->error("操作失败");
        }
    }
    /**
     * Undocumented 银行卡列表
     *
     * @return void
     */
    public function bank_card(){
        $list = Db::name("bank_card")->order("id",'desc')->where("mch_id",$this->request->auth_mch['mch'])->paginate(10,false,['query' =>$this->request->param()]);
        $page = $list->render();
        $this->assign("page",$page);
        $this->assign("list",$list);
        return view("bank_card");
    }
     /**
     * Undocumented 删除银行卡
     *
     * @return void
     */
    public function bankDelete(){
        $bank_id = $this->request->param("bank_id");
        if(empty($bank_id)){
            return $this->error("数据不存在");
        }
        Db::name("bank_card")->where("id",$bank_id)->delete();

        return $this->success("删除成功");
    }
    /**
     * Undocumented 提现申请
     *
     * @return void
     */
    public function withRequest(){
        $data = $this->request->param();
        $info = Db::name("mch_withdrawal_ip")->where("mch_id",$this->request->auth_mch['mch'])->find();
        if(empty($info)){
            return $this->error("请先绑定下发白名单");
        }
        if(!in_array(get_client_ip(),explode("|",$info['white_ip']))){
            return $this->error("当前IP未绑定");
        }
        
        if(!Googl_validation(Mch::get_mch_google($this->request->auth_mch['mch']),$data['google_code'])){
            //return $this->error("谷歌验证码错误");
        }
        //获取提现配置
        $with = config("custom.WITHDRAWAL");
        //判断提现时间段
        if(!empty($with['period_time'])){
            $period_time = explode("|",$with['period_time']);
            $time = strtotime(date('H:i',time()));//当前时间
           if($time > strtotime($period_time[0]) && $time > strtotime($period_time[1])){
                return $this->error('请在 '.$period_time[0].' - '.$period_time[1].' 内进行提现申请');
            }
        }
        $total_fee = abs($data['total_fee']);
        //判断单笔金额范围
        if($total_fee < $with['min_amount'] || $total_fee > $with['max_amount']){
            return $this->error('单笔提现金额最低 '.$with['min_amount'].' 元或最高 '.$with['max_amount'].' 元');
        }
        $balance = Mch::mch_balance($this->request->auth_mch['mch']);
        //判断是否超过提现金额
        if($total_fee > $balance){
            return $this->error('最大申请提现金额为：'.$balance.' 元');
        }
        //判断账号是否可以下发
        $info = Mch::where("mch",$this->request->auth_mch['mch'])->find();
        if(!empty($info)){
            if($info->chukuan == 2){
                return $this->error("账号已禁止出款,请联系管理员");
            }
        }else{
            return $this->error("账号不存在");
        }
        $result = Withdrawal::with_insert($this->request->auth_mch['mch'],$data['bank_id'],$data['total_fee'],$with['wht_fee'],$this->request->auth_mch['is_agent']);
        if($result === true){
            getMchLog($this->request->auth_mch['mch'],'申请提现,申请金额：'.$total_fee.'元',$this->request->auth_mch['is_agent']);
            return $this->success('申请提现成功，请等待');
        }else{
            return $this->error($result);
        }
    }
    /**
     * Undocumented 修改密码
     *
     * @return void
     */
    public function up_pwd(){
        $old_pwd = $this->request->param("old_pwd",'','strip_tags,trim');
        $new_pwd = $this->request->param("new_pwd",'','strip_tags,trim');
        $pwd = $this->request->param("pwd",'','strip_tags,trim');
        if($new_pwd == $old_pwd){
            return $this->error("新密码不能和旧密码相同");
        }
        if($new_pwd != $pwd){
            return $this->error("确认密码和新密码不一致");
        }
        $info = Mch::where("mch",$this->request->auth_mch['mch'])->find();
        $Aes = new \Aes();
        $o_pwd = $Aes->decrypt($info->password);//解密
        if($o_pwd != $old_pwd){
            return $this->error("旧密码输入错误");
        }
        $info->password = $Aes->encrypt($new_pwd);
        $info->save();
        getMchLog($this->request->auth_mch['mch'],'修改密码为：'.$new_pwd,$this->request->auth_mch['is_agent']);
        return $this->success("修改成功");
        
    }
    /**
     * Undocumented 商户信息
     *
     * @return void
     */
    public function material(){
        
        return view("material");
    }
    /**
     * Undocumented 重置秘钥
     *
     * @return void
     */
    public function reset_md5key(){
        
        $md5key = md5key(32);
        if($md5key){
            Mch::where("mch",$this->request->auth_mch['mch'])->update(array('md5key'=>md5($md5key)));
            //更新redis
            get_one_insert('mch',$this->request->auth_mch['mch'],Mch::where("mch",$this->request->auth_mch['mch'])->find());
            getMchLog($this->request->auth_mch['mch'],'重置秘钥',$this->request->auth_mch['is_agent']);
            return $this->success('重置成功');
        }else{
            return $this->error("重置失败");
        }
        
    }
}